<?php
namespace app\api\controller;

use app\wx_api\ext\auth\Sign;
use app\wx_api\model\UserModel;
use think\Controller;

/**
 * 平台微信应用api接口的基类，验证用户的
 * 登录与签名
 *
 * Class BaseController
 * @package app\api\controller
 */
class BaseController extends Controller
{
    // 微信用户的信息详情
    protected $user_info = [];

    /**
     * 微信用户登录验证
     * 客户端平台授权验证（签名验证）
     */
    public function initialize()
    {
        parent::initialize();

        $data = $this->request->param();
        if (empty($data['token'])) {
            //return json(['code' => 0, 'msg' => '缺失必要的参数token']);
            $this->redirect('login/index');// 跳转到登录请求
        }
        // 登录验证
        if (!$this->is_login($data['token'])) {
            $this->redirect('login/index');// 跳转到登录请求
            //return json(['code' => 0, 'msg' => '用户未登录']);
        }
        // 验证客户端是否是被授权的平台
        $signM = new Sign();
        if (!$signM->check($data)) {
            return json(['code' => 0, 'msg' => $signM->error_msg]);
        }
        return true; // 应该可以不用返回，多余的，哈哈
        //return json(['code' => 0, 'msg' => '非法访问形式,请使用post请求']);
    }

    /**
     * 判断用户是否已经登录
     *
     * @param $token
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function is_login($token) {
        $userM = new UserModel();
        if ($user = $userM->field(['created_time', 'updated_time', 'status', 'token'], true)->where(['token' => $token])->find()) {
            $this->user_info = $user->getData();
            return true;
        }
        return false;
    }
}
